<template>
  <div>
    <el-dialog v-model="dialogVisible" title="选择头像">
      <el-table ref="multipleTableRef" :data="listData" @selection-change="handleSelectionChange"
        :highlight-current-row="mode == 'radio'" @current-change="handleCurrentChange" row-key="id">

        <el-table-column type="selection" width="55" v-if="mode == 'multiple'" />

        <el-table-column label="id" property="id" />

        <el-table-column label="图片" width="800">
          <template #default="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.img" />
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="onConfirm">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang='ts' setup>
import { nextTick, onMounted, reactive, ref, toRaw } from 'vue'
import { ElMessageBox } from 'element-plus'
import { getBannerList, GetBannerSelectApi, ShopBannerAddAndEditApi } from '@/api/index'
import useTableHook from '@/hooks/useTableHook'
import { emit } from 'process'
import { ElTable } from 'element-plus'

const props = defineProps({
  mode: {
    type: String,
    default: 'radio'
  }
})

const multipleTableRef = ref<InstanceType<typeof ElTable>>()

const dialogVisible = ref(false)

const params = reactive({
  shopId: '',
  method: 'edit',
  bannerIds: ''
})

// onMounted(() => {
// })

const handleSelectionChange = (record) => {
  let chooseIds = record.map(item => item.id)

  params.bannerIds = chooseIds.join('|')
}

const handleCurrentChange = (record) => {

  params.bannerIds = record.id
}

const open = (config) => {
  getBannerListRequest()

  Object.assign(params, config.data)

  dialogVisible.value = true

  nextTick(() => {


  })
}

const setChooseImg = () => {
  let newStr = params.ids && params.ids.replace(/^\|(.*)\|$/, '$1');

  let chooseIdsArr = newStr.split('|')

  listData.value.filter(item => {
    let isHave = chooseIdsArr.find(cItem => item.id == cItem)

    if (isHave) {
      nextTick(() => {
        multipleTableRef.value.toggleRowSelection(item, true)
      })
    }
  })
}

const close = () => {
  dialogVisible.value = false
}

const onConfirm = async () => {
  try {
    const res = await ShopBannerAddAndEditApi(params)

    emit('confirm')

    close()
  } catch (error) {
    console.log('ShopCoverAddAndEditSubmit', error)
  }
}

const queryInfo = reactive({
  typeId: 1
})

const listData = ref([])

onMounted(() => {
})

const getBannerListRequest = async () => {
  try {
    const res = await GetBannerSelectApi(queryInfo)

    listData.value = res.data

    setChooseImg()
  } catch (error) {
    console.log('getBannerListRequest', error)
  }
}

const emit = defineEmits(['confirm'])

// 暴露方法给父组件
defineExpose({
  open
});
</script>

<style lang='scss' scoped></style>
